/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package multicast;

import common.MessageModel;
import common.Message_Type;
import common.Translate;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.sound.sampled.Port;

/**
 * 通过广播/组播发送开启的通信端口
 *
 * @author Eugene-Forest
 */
public class SendPortThread extends Thread {

    private final int destPort;

    public SendPortThread(int port) {
        this.destPort = port;
    }

    @Override
    public void run() {
        MulticastSocket multicastSocket;
        try {
            multicastSocket = new MulticastSocket(10000);
            // 必须使用D类地址
            InetAddress address = InetAddress.getByName("239.0.0.1");
            // 以D类地址为标识，加入同一个组才能实现广播
            multicastSocket.joinGroup(address);
            String message = String.valueOf(destPort);
            MessageModel messageModel=new MessageModel(Message_Type.Calling_Port,message);
            while (true) {
                byte[] buf = Translate.objectToByte(messageModel);
                DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length, address, 10000);
                multicastSocket.send(datagramPacket);
                Thread.sleep(5000);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
